package fragments;


import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.R;

import java.util.ArrayList;

import beans.NewUserInfoBean;
import beans.RegisterInfoBean;
import beans.UserInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import singleton.SingletonClass;
import utils.ToastUtil;

/**
 * A simple {@link Fragment} subclass.
 */
public class RegisterTypeFragment extends BaseFragment {
    @BindView(R.id.tv_register_type_fingerprint)
    TextView tvFingerprint;
    @BindView(R.id.tv_register_type_iris)
    TextView tvpeIris;
    Unbinder unbinder;
    @BindView(R.id.iv_type_rigister_back)
    ImageView ivBack;
    private RegisterInfoBean bean;
    private MyHandler allHandler;
    private Message message;

    public RegisterTypeFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_register_type, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        bean = (RegisterInfoBean) getArguments().getSerializable(Constants.REGISTER_TYPE_FRAGMENT);
        allHandler = SingletonClass.getSingleton(MyHandler.class);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.tv_register_type_fingerprint, R.id.tv_register_type_iris,R.id.iv_type_rigister_back})
    public void onViewClicked(View view) {
        message = allHandler.obtainMessage();
        message.obj = bean;
        switch (view.getId()) {
            case R.id.tv_register_type_fingerprint:
                message.what = HandlerConstant.FINGERPRINT_REGISTER;
                bean.setRegisterMode(Constants.FINGERPRINT_REGISTER);
                if (bean.getRegisterRole() != Constants.ROLE_SUPPLIER) {
                    getUserInfo(Constants.FINGERPRINT_REGISTER, "select * from UserInfo where UCode = '" + bean.getCode() + "'");
                } else {
                    if (bean.getRegisterRole() == Constants.ROLE_SUPPLIER) {
                        searchIdNumber(Constants.FINGERPRINT_REGISTER, bean.getIdNumber());
                    } else {
                        searchName(Constants.FINGERPRINT_REGISTER, "select * from UserInfo where UserName = '" + bean.getName() + "'");
                    }
                }
                break;
            case R.id.tv_register_type_iris:
                message.what = HandlerConstant.IRIS_REGISTER;
                bean.setRegisterMode(Constants.IRIS_REGISTER);
                if (bean.getRegisterRole() != Constants.ROLE_SUPPLIER) {
                    //判断员工编号是否已经注册过
                    getUserInfo(Constants.IRIS_REGISTER, "select * from UserInfo where UCode = '" + bean.getCode() + "'");
                } else {
                    if (bean.getRegisterRole() == Constants.ROLE_SUPPLIER) {
                        searchIdNumber(Constants.IRIS_REGISTER, bean.getIdNumber());
                    } else {
                        Log.e(TAG, "searchName");
                        searchName(Constants.IRIS_REGISTER, "select * from UserInfo where UserName = '" + bean.getName() + "'");
                    }
                }
                break;
            case R.id.iv_type_rigister_back :

                Message message = allHandler.obtainMessage();
                message.what = HandlerConstant.REGISTER_ROLE;
                message.obj = bean;
                allHandler.sendMessage(message);

                break;
        }
    }

    private void searchName(final int registerMode, String sql) {
        GetRetrofit.getInstance().getUserInfo(NetAddress.token, NetAddress.machineCode, sql)
                .enqueue(new Callback<ArrayList<UserInfoBean>>() {
                    @Override
                    public void onResponse(Call<ArrayList<UserInfoBean>> call, Response<ArrayList<UserInfoBean>> response) {
                        ArrayList<UserInfoBean> body = response.body();
                        if (registerMode == Constants.IRIS_REGISTER) {
                            hospitalIrisRegister(body);
                        } else {
                            hospitalFingerprintRegister(body);
                        }
                    }

                    @Override
                    public void onFailure(Call<ArrayList<UserInfoBean>> call, Throwable t) {

                    }
                });

    }


    private void getUserInfo(final int registerMode, String sql) {
        Call<ArrayList<UserInfoBean>> call = GetRetrofit.getInstance().getUserInfo(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<ArrayList<UserInfoBean>>() {
            @Override
            public void onResponse(Call<ArrayList<UserInfoBean>> call, Response<ArrayList<UserInfoBean>> response) {
                ArrayList<UserInfoBean> body = response.body();
                if (registerMode == Constants.IRIS_REGISTER) {
                    hospitalIrisRegister(body);
                } else {
                    hospitalFingerprintRegister(body);
                }
            }

            @Override
            public void onFailure(Call<ArrayList<UserInfoBean>> call, Throwable t) {

            }
        });
    }

    private void searchIdNumber(final int registerMode, String idNumber) {
        GetRetrofit.getInstance().getUserInfo2(NetAddress.token, NetAddress.machineCode, "select * from UserInfo where IDCardCode = '" + idNumber + "'")
                .subscribeOn(Schedulers.io()).groupBy(new Func1<NewUserInfoBean, Boolean>() {
            @Override
            public Boolean call(NewUserInfoBean userInfoBean) {
                return userInfoBean == null ? false : userInfoBean.getData().size() > 0;
            }
        }).observeOn(AndroidSchedulers.mainThread()).flatMap(new Func1<GroupedObservable<Boolean, NewUserInfoBean>, Observable<NewUserInfoBean.DataBean>>() {
            @Override
            public Observable<NewUserInfoBean.DataBean> call(GroupedObservable<Boolean, NewUserInfoBean> booleanUserInfoBeanGroupedObservable) {
                if (booleanUserInfoBeanGroupedObservable.getKey()) {
                    return booleanUserInfoBeanGroupedObservable.subscribeOn(Schedulers.io()).flatMap(new Func1<NewUserInfoBean, Observable<NewUserInfoBean.DataBean>>() {
                        @Override
                        public Observable<NewUserInfoBean.DataBean> call(NewUserInfoBean userInfoBean) {
                            return Observable.from(userInfoBean.getData()).last();
                        }
                    });
                } else {
                    ToastUtil.showToast(mContext, "该身份证号尚未注册,请先在手持机上面注册");
                    return null;
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<NewUserInfoBean.DataBean>() {
            @Override
            public void call(final NewUserInfoBean.DataBean dataBean) {

                if (registerMode == Constants.IRIS_REGISTER) {
                    supplierIrisRegister(dataBean);
                } else {
                    supplierFingerprintRegister(dataBean);
                }
            }
        }, new MyAction1());
    }

    private void hospitalFingerprintRegister(ArrayList<UserInfoBean> body) {
        if (body.size() > 0) {
            String fingerprintOne = body.get(0).getFingerprintOne();
            String fingerprintTwo = body.get(0).getFingerprintTwo();
            if (!TextUtils.isEmpty(fingerprintOne) && !TextUtils.isEmpty(fingerprintTwo)) {
                Log.e(TAG, "hospitalFingerprintRegister: 1");
                ToastUtil.showToast(mContext, "此员工编号已经注册过了");
            } else {
                Log.e(TAG, "hospitalFingerprintRegister: 2");
                bean.setPut(true);
                if (!TextUtils.isEmpty(fingerprintOne)) {
                    bean.setOneFingerprintRegister(true);
                }
                allHandler.sendMessage(message);
            }
        } else {
            bean.setPut(false);
            allHandler.sendMessage(message);
        }
    }

    private void hospitalIrisRegister(ArrayList<UserInfoBean> body) {
        if (body.size() > 0) {
            String leftImg = body.get(0).getLeftImg();
            if (!TextUtils.isEmpty(leftImg)) {
                ToastUtil.showToast(mContext, "此员工编号已经注册过了");
            } else {
                bean.setPut(true);
                allHandler.sendMessage(message);
            }
        } else {
            bean.setPut(false);
            allHandler.sendMessage(message);
        }
    }

    private void supplierIrisRegister(NewUserInfoBean.DataBean dataBean) {
        if (TextUtils.isEmpty(dataBean.getLeftImg())) {
            allHandler.sendMessage(message);
        } else {
            ToastUtil.showToast(mContext, "虹膜已经注册过了");
        }
    }

    private void supplierFingerprintRegister(NewUserInfoBean.DataBean dataBean) {
        String fingerprintOne = dataBean.getFingerprintOne();
        String fingerprintTwo = dataBean.getFingerprintTwo();
        if (!TextUtils.isEmpty(fingerprintOne) && !TextUtils.isEmpty(fingerprintTwo)) {
            ToastUtil.showToast(mContext, "指纹已经注册过了");
        } else {
            if (!TextUtils.isEmpty(fingerprintOne)) {
                bean.setOneFingerprintRegister(true);
            }
            allHandler.sendMessage(message);
        }

    }
}
